import json
from datetime import datetime, timedelta
import jwt
from django.core.serializers.json import DjangoJSONEncoder
from django.forms import model_to_dict
from django.contrib import auth
from rest_framework.pagination import PageNumberPagination
from rest_framework.response import Response
from rest_framework.views import APIView
from django.contrib.auth.models import User
from userManager.models import UserRole

import airport_logistics_backend.settings
from userManager.serializers import UserSerializer


def getUserByToken(token):
    user_info = jwt.decode(token, airport_logistics_backend.settings.SECRET_KEY, algorithms=["HS256"])
    user = User.objects.get(id=user_info["user_id"])
    return user

def writeUser(user):
    user_dict = {
        'userId': user.id,
        'realName': user.username,
        'email': user.email,
        'img': user.userrole.img,
        'jnumber': user.userrole.jnumber,
        'phone': user.userrole.phone,
        'gender': user.userrole.gender,
        'createDate': user.date_joined.strftime('%Y-%m-%d %H:%M:%S')
    }
    json_data = json.dumps(user_dict, indent=2)
    return json_data

class LoginViews(APIView):
    @staticmethod
    def post(request, *args, **kwargs):
        username = request.data.get("username", "")
        password = request.data.get("password", "")

        # auth是Django中创建的默认的表，默认创建了一些字段的
        user = auth.authenticate(username=username, password=password)
        if user is not None:
            payload = {
                'user_id': user.id,
                'username': user.username,
                'exp': datetime.utcnow() + timedelta(hours=2),
                'iat': datetime.utcnow()
            }
            # 创建token
            token = jwt.encode(payload, airport_logistics_backend.settings.SECRET_KEY, algorithm='HS256')
            # # 保存token到session当中
            # request.session["token"] = token
            # 序列化User
            user_json = model_to_dict(user)
            return Response(data={
                'user': json.dumps(user_json, ensure_ascii=False, cls=DjangoJSONEncoder),
                'token': token,
                'messages': '登录成功！'
            }, status=200)
        else:
            return Response(status=400)


class LoginInfo(APIView):
    @staticmethod
    def get(request, *args, **kwargs):
        req_token = request.query_params.get("token")

        # 传入的token和session中保存的token相同
        if req_token:
            user = getUserByToken(req_token)
            user_role = user.userrole
            if user:
                user_json = UserSerializer(user)
                return Response(data={
                    "user_info": user_json.data,
                    "role": user_role.role,
                }, status=200)
            else:
                return Response(status=500)
        else:
            return Response(status=500)


class LogOut(APIView):
    @staticmethod
    def post(request, *args, **kwargs):
        req_token = request.data.get("token")
        # 传入的token进行解析，然后获取用户
        if req_token:
            user = getUserByToken(req_token)
            if user:
                return Response(status=200)
            else:
                return Response(status=500)
        else:
            return Response(status=500)


class getUserList(APIView):
    @staticmethod
    def get(request, *args, **kwargs):
        userInfo = request.query_params.get("userInfo")
        queryParams = request.query_params.get("queryParams")
        queryParams_json = json.loads(queryParams)
        page_Num = queryParams_json['pageNum']
        page_size = queryParams_json['pageSize']
        if userInfo:
            userInfo = json.loads(userInfo)
            if userInfo["realName"]:
                print("根据用户名返回用户列表")
                user = User.objects.get(username=userInfo["realName"])
                json_data = writeUser(user)
                return Response(status=200, data=json_data)
        else:
            print("返回全部用户列表")
            userList = User.objects.all()
            paginator = PageNumberPagination()
            paginator.page_size = page_size
            users_page = paginator.paginate_queryset(userList, request)
            serializer = UserSerializer(users_page, many=True)
            response_data = {
                'total': userList.count(),
                'pageNum': page_Num,
                'pageSize': page_size,
                'data': serializer.data
            }
            return Response(status=200, data=response_data)


class addUser(APIView):
    @staticmethod
    def post(request, *args, **kwargs):
        user_origin = request.data.get("userInfo")
        if user_origin:
            user = User.objects.create_user(username=user_origin['realName'], password=user_origin['password']
                                            , email=user_origin['email'])
            user.date_joined = datetime.utcnow()

            user_role = UserRole(user=user)
            user_role.role = 'editor'
            user_role.jnumber = user_origin['jnumber']
            user_role.img = user_origin['img']
            user_role.phone = user_origin['phone']
            user_role.gender = user_origin['gender']
            user.save()
            user_role.save()
            return Response(status=200)
        else:
            return Response(status=500)

class getUser(APIView):
    @staticmethod
    def post(request, *args, **kwargs):
        userId = request.data.get("userId")
        if userId:
            user = User.objects.get(id=userId)
            json_data = writeUser(user)
            return Response(status=200, data=json_data)
        else:
            return Response(status=500)

class editUser(APIView):
    @staticmethod
    def post(request, *args, **kwargs):
        user_origin = request.data.get("userInfo")
        print(user_origin)
        if user_origin:
            user = User.objects.get(id=user_origin['userId'])
            if user:
                if user_origin['password']:
                    user.set_password(user_origin['password'])
                user_role = user.userrole
                user.username = user_origin['realName']
                user.email = user_origin['email']
                user_role.phone = user_origin['phone']
                user_role.jnumber = user_origin['jnumber']
                user_role.img = user_origin['img']
                user_role.gender = user_origin['gender']

                user.save()
                user_role.save()
                return Response(status=200)
            else:
                return Response(status=500)

class resetPassword(APIView):
    @staticmethod
    def post(request, *args, **kwargs):
        userId = request.data.get("userId")
        new_password = "123456"
        if userId:
            try:
                user_to_update = User.objects.get(id=userId)
                user_to_update.set_password(new_password)
                user_to_update.save()
                return Response(status=200)
            except User.DoesNotExist:
                # 用户不存在
                print("用户不存在")
            except Exception as e:
                # 修改密码失败，捕获异常并打印错误消息
                print(f"密码修改失败：{str(e)}")
                return Response(status=200, exception=str(e))

class deleteUser(APIView):
    @staticmethod
    def post(request, *args, **kwargs):
        userId = request.data.get("userId")
        if userId:
            user = User.objects.get(id=userId)
            count = user.delete()
            print(count[0])
            if count[0] > 0:
                return Response(status=200)
            else:
                return Response(status=500)
        else:
            return Response(status=500)
